//
//  KLShopCartViewController.m
//  KunLun
//
//  Created by Mac on 2017/11/25.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "KLShopCartViewController.h"
#import "KLShopCartTableViewCell.h"
#import "KLShopCarModel.h"
#import "KLBuyNowViewController.h"
@interface KLShopCartViewController ()
@property(nonatomic, strong) STButton                     *rightButton;
@property(nonatomic, strong) STButton                     *allButton;//全选
@property(nonatomic, strong) STLabel                     *moneyLable;//金额
@property(nonatomic, strong) STButton                     *cofrimButton;//购买或者删除
@property(nonatomic, strong) UIView                     *bootomView;
@property(nonatomic, strong) NSMutableArray<KLShopCarModel*>                     *dataSouce;
@property(nonatomic, strong) STNoresultView                     *noResultView;
@end

@implementation KLShopCartViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = self.tableView.backgroundColor;
    self.title = @"购物车";
    [self configSubView];

    self.automaticallyAdjustsScrollViewInsets = NO;
    if (IOS11 && [self.tableView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
        [self.tableView setContentInsetAdjustmentBehavior:@(2)];
    }
    self.tableView.frame = CGRectMake(0, [KLUtils navgationBarBootom], UIScreenWidth, self.bootomView.top - [KLUtils navgationBarBootom]);
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self sendMyshopCarListRequest];
    }];
    [self.tableView.mj_header beginRefreshing];
    
    self.noResultView = [[STNoresultView alloc] initWithFrame:CGRectMake(0, self.tableView.tableHeaderView.height + 120, UIScreenWidth, 350)
                                                        title:@"购物车空空如也"
                                                  buttonTitle:@""
                                                 buttonHandle:^(NSString *titleString) {
                                                     
                                                 }];
    self.noResultView.hidden = YES;
    [self.tableView addSubview:self.noResultView];
    
    // Do any additional setup after loading the view.
}
- (void)reloadData{
    self.noResultView.hidden = self.dataSouce.count;
    self.bootomView.hidden = !self.dataSouce.count;
    
    self.moneyLable.text = [NSString stringWithFormat:@"合计:%0.2f",[self cacluateMoney]];
    self.moneyLable.attributedText = [self.moneyLable.text st_convertAttributeStringWithKeyWord:@"合计:"
                                                                                     attributes:@{NSForegroundColorAttributeName:KL_firstTextColor}];
    
    [self.tableView reloadData];
}
- (CGFloat)cacluateMoney{
    CGFloat money = 0   ;
    for (int i = 0 ; i < self.dataSouce.count; i ++) {
        for (KLGoodModel * model in self.dataSouce[i].goods) {
            if (model.selected) {
               money = money + model.number.integerValue * model.price.floatValue;
            }
            
        }
    }
    return money;
}
- (void)makeAllGoodSlectedState:(BOOL)selected{
    for (int i = 0 ; i < self.dataSouce.count; i ++) {
        for (KLGoodModel * model in self.dataSouce[i].goods) {

            model.selected = selected;
        }
    }
}
- (BOOL)judgeAllGoodIsSelected{
    for (int i = 0 ; i < self.dataSouce.count; i ++) {
        for (KLGoodModel * model in self.dataSouce[i].goods) {
            
            if (!model.selected) {
                return NO;
            }
        }
    }
    return YES;
}
- (BOOL)judgeISExistSelectedModel{
    for (int i = 0 ; i < self.dataSouce.count; i ++) {
        for (KLGoodModel * model in self.dataSouce[i].goods) {
            
            if (model.selected) {
                return YES;
            }
        }
    }
    return NO;
}
- (NSArray*)slectedGoodIDArray{
    NSMutableArray * array = [NSMutableArray new];
    for (int i = 0 ; i < self.dataSouce.count; i ++) {
        for (KLGoodModel * model in self.dataSouce[i].goods) {
            
            if (model.selected) {
                [array addObject:model.goodID.description];
            }
        }
    }
    return array;
}
- (NSArray<NSArray*>*)configBuyDataSouce{
    NSMutableArray * finshArray = [NSMutableArray new];
    for (int i = 0 ; i < self.dataSouce.count; i ++) {
        KLShopCarModel * shopModel = self.dataSouce[i];
        NSMutableArray * shop = [NSMutableArray new];
        for (KLGoodModel * model in self.dataSouce[i].goods) {

            if (model.selected) {
                
                NSDictionary * dic = model.mj_keyValues;
                KLGoodDetailModel * goodDetailModel = [KLGoodDetailModel mj_objectWithKeyValues:dic];
                goodDetailModel.shops = [KLShopModel new];
                goodDetailModel.shops.shops_name = shopModel.shops_name;
                goodDetailModel.shops.gategoryID = shopModel.shops_id;
                goodDetailModel.shops.head_portrait = shopModel.head_portrait;
                goodDetailModel.num = model.number.integerValue;
                goodDetailModel.cover_map = @[goodDetailModel.exhibition_map];
                [shop addObject:goodDetailModel];
            }
        }
        if (shop.count) {
            [finshArray addObject:shop];
        }
    }
    return finshArray;
}
#pragma mark --subView
- (void)configSubView{
    __weak typeof(self) weakSelf =  self;
    self.rightButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 60, 40)
                                                     title:@"编辑"
                                                titleColor:[UIColor whiteColor]
                                                 titleFont:14
                                              cornerRadius:0
                                           backgroundColor:[UIColor clearColor]
                                           backgroundImage:nil
                                                     image:nil];
    [self.rightButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
     [self.rightButton setTitle:@"完成" forState:UIControlStateSelected];
    [self st_setRightItemWithView:self.rightButton];
    [self configBootomeView];
}
- (void)configBootomeView{
    UIView  * bootomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 50)];
    bootomView.bottom = [KLUtils tabBarTop];
    bootomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bootomView];
    [bootomView st_showTopShadow];
    [bootomView st_showBottomLine];
    bootomView.hidden = YES;
    self.bootomView = bootomView;
    __weak typeof(self) weakSelf =  self;
    self.allButton = [[STButton alloc] initWithFrame:CGRectMake(10, 0, 60, 49)
                                                     title:@"全选"
                                                titleColor:KL_firstTextColor
                                                 titleFont:14
                                              cornerRadius:0
                                           backgroundColor:nil
                                           backgroundImage:nil
                                                     image:[UIImage imageNamed:@"购物未选中"]];
    self.allButton.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
    [self.allButton setImage:[UIImage imageNamed:@"购物选中"] forState:UIControlStateSelected];
    [self.allButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedAllButton];
    }];
    [bootomView addSubview:self.allButton];
    
    self.cofrimButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 120, 49)
                                                     title:@"结算"
                                                titleColor:[UIColor whiteColor]
                                                 titleFont:15
                                              cornerRadius:0
                                           backgroundColor:KL_BlueBackGroundColor
                                           backgroundImage:nil
                                                     image:nil];
    self.cofrimButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [self.cofrimButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedConfimButton];
    }];
    self.cofrimButton.showsTouchWhenHighlighted = NO;
    self.cofrimButton.right = UIScreenWidth;
    [bootomView addSubview:self.cofrimButton];
    
    self.moneyLable = [[STLabel alloc] initWithFrame:CGRectMake(self.allButton.right + 10, 0, self.cofrimButton.left - self.allButton.right - 20, 49)
                                                text:@"合计:$5698"
                                                textColor:KL_redColor
                                                     font:13
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentCenter];
    self.moneyLable.attributedText = [self.moneyLable.text st_convertAttributeStringWithKeyWord:@"合计:"
                                                                                     attributes:@{NSForegroundColorAttributeName:KL_firstTextColor}];
    [bootomView addSubview:self.moneyLable];
    
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.dataSouce.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce[section].goods.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [KLShopCartTableViewCell cellHeight];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 54;;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    __weak typeof(self) weakSelf =  self;
    NSString * title = self.dataSouce[section].shops_name;
    UIView * sectionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth , 64)];
    sectionView.backgroundColor = self.tableView.backgroundColor;
    STButton * buyButton = [[STButton alloc] initWithFrame:CGRectMake(0, 10, UIScreenWidth, 44)
                                                     title:title
                                                titleColor:KL_firstTextColor
                                                 titleFont:15
                                              cornerRadius:0
                                           backgroundColor:[UIColor whiteColor]
                                           backgroundImage:nil
                                                     image:[UIImage imageNamed:@"我的渠道"]];
    [buyButton setImage:[UIImage imageNamed:@"我的渠道"] forState:UIControlStateSelected];
    buyButton.imageEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    buyButton.titleEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0);
    [buyButton setClicAction:^(UIButton *sender) {
        sender.selected = !sender.selected;
    }];
    [sectionView addSubview:buyButton];
    return sectionView;
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    KLShopCartTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[KLShopCartTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        
    }
    __weak typeof(self) weakSelf =  self;
    cell.goodModel = self.dataSouce[indexPath.section].goods[indexPath.row];
    [cell.chosedButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedChosedButtonWithIndexPath:indexPath];
    }];
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    KLGoodModel * mdoel = self.dataSouce[indexPath.section].goods[indexPath.row];
    KLGoodDetailViewController * vc = [KLGoodDetailViewController new];
    vc.goodID = mdoel.goodID.description;
    [self.navigationController pushViewController:vc animated:YES];
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}
#pragma mark --Action Method
- (void)onSelctedChosedButtonWithIndexPath:(NSIndexPath*)indexPath{
    KLGoodModel *  goodModel = self.dataSouce[indexPath.section].goods[indexPath.row];
    goodModel.selected = !goodModel.selected;
    [self reloadData];
    self.allButton.selected = [self judgeAllGoodIsSelected];
}
- (void)st_rightBarAction:(id)sender{
    self.rightButton.selected = !self.rightButton.selected;
    if (self.rightButton.selected) {
            [self.cofrimButton setTitle:@"删除" forState:UIControlStateNormal];
            [self.cofrimButton st_showAnimationWithType:STAnimationTypecube duration:0.25];
    }else{
            [self.cofrimButton setTitle:@"结算" forState:UIControlStateNormal];
            [self.cofrimButton st_showAnimationWithType:STAnimationTypecube duration:0.25];
    }
  
}
- (void)onSelectedAllButton{
    self.allButton.selected = !self.allButton.selected;
    [self makeAllGoodSlectedState:self.allButton.selected];
    [self reloadData];
}
- (void)onSelectedConfimButton{
    if (![self judgeISExistSelectedModel]) {
        [SVProgressHUD showErrorWithStatus:@"你还未勾选任何商品"];
        return;
    }

    if ([self.cofrimButton.currentTitle isEqualToString:@"删除"]) {
        NSArray * goodIDS = [self slectedGoodIDArray];
        [self sendDelGoodWithArray:goodIDS];
    }else{
        //去订单
        KLBuyNowViewController * vc= [KLBuyNowViewController new];
        //self.goooDetailModel.num = [self.header.autoView.currentNum integerValue];
        vc.dataSouce = [self configBuyDataSouce];
        vc.from = @"cart";
        [self.navigationController pushViewController:vc animated:YES];
    }
}
#pragma mark --NetWork Method
- (void)sendMyshopCarListRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/user/shopping",[NSString stringWithFormat:@"?token=%@",[STUserManger defult].token]];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 self.dataSouce = [NSMutableArray new];
                                                 NSDictionary * dataDic =  responseObject[@"data"];
                                                 NSLog(@"json = %@",dataDic.mj_JSONString);
                                                 if ([dataDic.allKeys containsObject:@"goods_list"]) {
                                                     NSArray * array = dataDic[@"goods_list"];
                                                     for (NSDictionary * shopDic in array) {
                                                         KLShopCarModel * model =  [KLShopCarModel mj_objectWithKeyValues:shopDic];
                                                         NSArray * goodArray = shopDic[@"goods"];
                                                         NSMutableArray * goodmodels = [NSMutableArray new];
                                                         for (NSDictionary  *goodic in goodArray) {
                                                             KLGoodModel * goodModel = [KLGoodModel mj_objectWithKeyValues:goodic];
                                                             [goodmodels addObject:goodModel];
                                                         }
                                                         model.goods = goodmodels;
                                                         [self.dataSouce addObject:model];
                                                     }
                                                 }
                                                 [self reloadData];
                                                //[SVProgressHUD showSuccessWithStatus:@"ss"];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [self reloadData];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                                 
                                                 
                                             }];
}
- (void)sendDelGoodWithArray:(NSArray*)goodIDsS{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/user/delshopping",[NSString stringWithFormat:@"?token=%@",[STUserManger defult].token]];
    NSString * ids = [goodIDsS componentsJoinedByString:@","];
    if (ids.length) {
        [dic setObject:ids forKey:@"id"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showSuccessWithStatus:@"删除成功"];
                                                 [self.tableView.mj_header beginRefreshing];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                                 
                                                 
                                             }];
}

@end
